package com.hw.backapi.context;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hw.common.contants.RedisKeyContants;
import com.hw.common.enums.RoleEnums;
import com.hw.common.exception.BaseException;
import com.hw.common.utils.JwtUtils;
import com.hw.model.common.ResultCode;
import com.hw.model.entity.AdminPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 用户登录上下文
 */
@Component
public class UserAuthContext {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 获取用户信息
     * @return
     */
    public AdminPO getUserInfo(){
        String token = JwtUtils.getAdminTokenByJwtToken();

        String userInfo = stringRedisTemplate.opsForValue().get(RedisKeyContants.TOKEN + token);
        if(StrUtil.isEmpty(userInfo)){
            throw new BaseException(ResultCode.NOLOGIN,"Not log in");
        }
        AdminPO adminPO = JSONUtil.toBean(userInfo, AdminPO.class);
        return adminPO;
    }

    /**
     * 检查用户操作权限
     * @param adminPO
     * @return
     */
    public void checkLoginUserOperationAuthority(AdminPO adminPO){
        if( adminPO.getRole() <= RoleEnums.ADMIN.getCode() ){
            throw new BaseException("permission denied");
        }
    }

    /**
     * 退出登录
     */
    public void logout(){
        //获取token
        String token = JwtUtils.getAdminTokenByJwtToken();

        stringRedisTemplate.delete(RedisKeyContants.TOKEN + token);
    }

    /**
     * 校验角色a是否大于角色b的权限： 角色id越大，权限越大
     * @param roleIdA
     * @param roleIdB
     * @return
     */
    public boolean checkRole(int roleIdA , int roleIdB){
        return roleIdA > roleIdB;
    }
}
